#! /usr/bin/env python3
# -*- coding: UTF-8 -*-


import re
import time


def tracelog_to_csv(log, csv, csv_call):
    flog = open(log, 'r')
    fcsv = open(csv, 'w')
    fcal = open(csv_call, 'w')

    is_call = False
    i = 0
    for row in flog:
        i += 1
        try:
            if is_call:
                if '=>' in row:
                    call = row.split()[1]
                    fcal.write(f'{call}|')
                else:
                    is_call = False
                    fcal.write(f'\n')

            if 'kmalloc:' in row:
                row = re.sub('[\[\]:]|ptr=|bytes_alloc=', '', row)
                col = row.split()
                task, pid = col[0].rsplit('-', 1)
                fcsv.write(f'{task} {pid} {col[1]} {col[2]} {col[3]} {col[6]} {col[8]}\n')
            elif 'kfree:' in row:
                row = re.sub('[\[\]:]|ptr=', '', row)
                col = row.split()
                task, pid = col[0].rsplit('-', 1)
                fcsv.write(f'{task} {pid} {col[1]} {col[2]} {col[3]} {col[6]} 0\n')
            elif 'kernel_stack:' in row:
                row = re.sub('[\[\]]', '', row)
                col = row.split()
                task, pid = col[0].rsplit('-', 1)
                is_call = True
                fcal.write(f'{task} {pid} {col[1]} ')


        except Exception as e:
            print(f'line: {i} exception: {e}')
    fcsv.close()
    fcal.close()
    flog.close()


if __name__ == '__main__':
    import time
    import sys

    t0 = time.time()
    #load_tracelog(sys.argv[1])
    tracelog_to_csv('trace.log', 'trace.csv', 'call.csv')
    t1 = time.time()
    print(f'time:{t1-t0:.4f}')
